import { getTextVisualLength } from "./globalMgr.js";

export class DatabaseAPI {
    static async updateDatabase(action, data) {
        try {
            console.groupCollapsed(`[Database] ${action} request`);
            console.info('Sending data:', data);

            const response = await fetch('/network/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ action, ...data })
            });

            const result = await response.json();

            if (result.logs) {
                console.info('Server logs:');
                result.logs.forEach(log => console.info(log));
            }

            console.info('Response:', result);
            console.groupEnd();

            if (action === 'add_node' && !result.id) {
                throw new Error('Server did not return node ID');
            }

            return result;
        } catch (error) {
            console.error('Database error:', error);
            return { status: 'error', message: error.message };
        }
    }

    static async addNode(name, description, x, y, color, desc_type = 'plain', connections = []) {
        const result = await this.updateDatabase('add_node', {
            label: name,
            description,
            x_position: x,
            y_position: y,
            color,
            desc_type
        });
        
        if (!result.id) {
            throw new Error('Failed to get node ID from server');
        }
        
        return {
            id: result.id,
            name,
            description,
            desc_type: desc_type || 'plain',
            radius: Math.max(15, Math.ceil((getTextVisualLength(name) * 14 * 0.6 + 10) / 2)),
            color: color || '#4285f4',
            expanded: false,
            x,
            y
        };
    }

    static async addConnection(sourceId, targetId) {
        return await this.updateDatabase('add_connection', { source_id: sourceId, target_id: targetId });
    }

    static async removeNode(nodeId) {
        return await this.updateDatabase('remove_node', { id: nodeId });
    }

    static async removeConnection(sourceId, targetId) {
        return await this.updateDatabase('remove_connection', {
            source_id: sourceId,
            target_id: targetId
        });
    }

    /**
     * 更新节点描述信息
     * @param {Number} nodeId - 节点ID
     * @param {string} description - 新的描述内容
     * @param {string} desc_type - 描述类型(plain/markdown/html)
     * @returns {Object} 操作结果
     */
    static async updateNodeDescription(nodeId, description, desc_type = 'plain') {
        return await this.updateDatabase('update_node_description', {
            id: nodeId,
            description,
            desc_type
        });
    }
}

// 将ApiService暴露到全局作用域
window.DatabaseAPI = DatabaseAPI;